//
//  ChangeTimeVC.m
//  Wallets Manager
//
//  Created by Nguyen Chi Cong on 10/28/12.
//  Copyright (c) 2012 BKHN. All rights reserved.
//

#import "ChangeTimeVC.h"
#import <QuartzCore/QuartzCore.h>
#import "folyAppDelegate.h"
#import "Global.h"

@implementation ChangeTimeVC
{
    SVSegmentedControl *grayRC;
    NSDate *fromeDate;
    NSDate *toDate;
    NSInteger currentYear;
    QuarterType currentQuarter;
    MonthType currentMonth;
    NSNumber *numTimeMode;
    NSDateFormatter *dateFormatter;
    NSInteger tagForDate;
}
@synthesize imvBorder;
@synthesize viewMonthMode;
@synthesize viewQuarterMode;
@synthesize viewCustomMode;
@synthesize viewContainer;
@synthesize txtMMYear;
@synthesize txtMMMonth;
@synthesize txtQMYear;
@synthesize txtQMQuarter;
@synthesize txtCMFrom;
@synthesize txtCMTo;
@synthesize monthViewCalendar;
@synthesize pickerViewPopup;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    //Init segment control
    grayRC = [[SVSegmentedControl alloc] initWithSectionTitles:[NSArray arrayWithObjects:@"Month", @"Quarter",@"Custom", nil]];
    [grayRC addTarget:self action:@selector(segmentedControlChangedValue:) forControlEvents:UIControlEventValueChanged];
    
	grayRC.font = [UIFont boldSystemFontOfSize:12];
	grayRC.titleEdgeInsets = UIEdgeInsetsMake(0, 5, 0, 5);
	grayRC.height = 30;
	
	grayRC.thumb.tintColor = [UIColor colorWithRed:0 green:0.5 blue:0.1 alpha:1];
	
	[self.view addSubview:grayRC];
	
	grayRC.center = CGPointMake(160, 170);
    
    //Set up Border
    viewMonthMode.layer.borderWidth = 1.0f;
    viewMonthMode.layer.cornerRadius = 10.0f;
    viewQuarterMode.layer.borderWidth = 1.0f;
    viewQuarterMode.layer.cornerRadius = 10.0f;
    viewCustomMode.layer.borderWidth = 1.0f;
    viewCustomMode.layer.cornerRadius = 10.0f;
    
    txtMMMonth.layer.borderWidth = 1.0f;
    txtMMMonth.layer.cornerRadius = 10.0f;
    txtMMYear.layer.borderWidth = 1.0f;
    txtMMYear.layer.cornerRadius = 10.0f;
    txtQMYear.layer.borderWidth = 1.0f;
    txtQMYear.layer.cornerRadius = 10.0f;
    txtQMQuarter.layer.borderWidth = 1.0f;
    txtQMQuarter.layer.cornerRadius = 10.0f;
    txtCMTo.layer.borderWidth = 1.0f;
    txtCMTo.layer.cornerRadius = 10.0f;
    txtCMFrom.layer.borderWidth = 1.0f;
    txtCMFrom.layer.cornerRadius = 10.0f;
    
    //initFormat
    dateFormatter = [[NSDateFormatter alloc]init];
    [dateFormatter setDateFormat:@"MM/dd/yyyy"];
    
    [self performSelector:@selector(resetTime)];
    
}

-(void)viewWillAppear:(BOOL)animated
{
    [self performSelector:@selector(refreshField)];
    [super viewWillAppear:animated];
}

-(void)resetTime
{
    //init current data
    NSDate *today = [NSDate date];
    
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDateComponents *dateCompoents = [calendar components:NSMonthCalendarUnit|NSQuarterCalendarUnit|NSYearCalendarUnit fromDate:today];
    currentMonth = [dateCompoents month];
    currentYear = [dateCompoents year];
    currentQuarter = ((currentMonth%3) != 0?(currentMonth/3+1):currentMonth/3);
    fromeDate = [NSDate dateWithYear:currentYear month:currentMonth day:1];
    toDate = [NSDate dateWithYear:(currentMonth<12?currentYear:currentYear+1) month:(currentMonth<12?currentMonth+1:1) day:1];
    
    [self performSelector:@selector(refreshField)];
}

-(void)refreshField
{
    txtMMMonth.text = [NSString stringWithFormat:@"%i", currentMonth];
    txtMMYear.text = [NSString stringWithFormat:@"%i", currentYear];
    
    txtQMQuarter.text = [NSString stringWithFormat:@"%i", currentQuarter];
    txtQMYear.text = [NSString stringWithFormat:@"%i", currentYear];
    txtQMYear.text = [NSString stringWithFormat:@"%i", currentYear];
    txtCMFrom.text = [dateFormatter stringFromDate:fromeDate];
    txtCMTo.text = [dateFormatter stringFromDate:toDate];
}

- (void)segmentedControlChangedValue:(SVSegmentedControl*)segmentedControl
{
    [self refreshField];
    numTimeMode = [NSNumber numberWithInt:segmentedControl.selectedIndex];
    
    CATransition *animation = [CATransition animation];
	animation.delegate = self;
	animation.duration = 0.3f;
    animation.type = kCATransitionFade;
    animation.subtype = kCATransitionFromLeft;
    
    NSLog(@"INDEX = %i", segmentedControl.selectedIndex);
    switch (segmentedControl.selectedIndex) {
            
        case 0:
            [viewContainer bringSubviewToFront:viewMonthMode];
            break;
        case 1:
            [viewContainer bringSubviewToFront:viewQuarterMode];
            break;
        case 2:
            [viewContainer bringSubviewToFront:viewCustomMode];
            break;
            
        default:
            break;
    }
    
    [viewContainer.layer addAnimation:animation forKey:@"animation"];
}

- (void)viewDidUnload
{
    [self setImvBorder:nil];
    [self setViewMonthMode:nil];
    [self setViewQuarterMode:nil];
    [self setViewCustomMode:nil];
    [self setViewContainer:nil];
    [self setTxtMMYear:nil];
    [self setTxtMMMonth:nil];
    [self setTxtQMYear:nil];
    [self setTxtQMQuarter:nil];
    [self setTxtCMFrom:nil];
    [self setTxtCMTo:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
    grayRC          = nil;
    dateFormatter   = nil;
    fromeDate       = nil;
    toDate          = nil;
    numTimeMode     = nil;
    monthViewCalendar = nil;
    pickerViewPopup   = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - IBAction
- (IBAction)backView:(id)sender {
    
}
- (IBAction)doneAction:(id)sender {
    
    NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDateComponents *components = [gregorianCalendar components:NSDayCalendarUnit|NSMonthCalendarUnit|NSYearCalendarUnit fromDate:toDate];
    
    switch ([numTimeMode intValue]) {
        case 0:
            fromeDate = [NSDate dateWithYear:currentYear month:currentMonth day:1];
            toDate = [NSDate dateWithYear:(currentMonth<12?currentYear:currentYear+1) month:(currentMonth<12?currentMonth+1:1) day:1];
            break;
        case 1:
        {
            if(currentQuarter == 1)
            {
                fromeDate = [NSDate dateWithYear:currentYear month:1 day:1];
                toDate = [NSDate dateWithYear:currentYear month:4 day:1];
            }else if(currentQuarter == 2)
            {
                fromeDate = [NSDate dateWithYear:currentYear month:4 day:1];
                toDate = [NSDate dateWithYear:currentYear month:7 day:1];
            }else if(currentQuarter == 3)
            {
                fromeDate = [NSDate dateWithYear:currentYear month:7 day:1];
                toDate = [NSDate dateWithYear:currentYear month:10 day:1];
            }else
            {
                fromeDate = [NSDate dateWithYear:(currentYear) month:10 day:1];
                toDate = [NSDate dateWithYear:(currentYear+1) month:1 day:1];
            }
        }
            break;
        case 2:
        {
            NSInteger day = [components day];
            day++;
            [components setDay:day];
            toDate = [gregorianCalendar dateFromComponents:components];
        }
            break;
            
        default:
            break;
    }
    
    NSDictionary *dict = [[NSDictionary alloc] initWithObjectsAndKeys:fromeDate,@"fromDate", toDate, @"toDate", nil];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"ChangeTimeMode" object:numTimeMode userInfo:dict];
    
    NSInteger day = [components day];
    day --;
    [components setDay:day];
    toDate = [gregorianCalendar dateFromComponents:components];
    
    [UIView beginAnimations:@"push_animation" context:NULL];
    [UIView setAnimationDuration:0.3];
    [UIView setAnimationBeginsFromCurrentState:YES];
    
    [self.view setFrame:CGRectMake(0, 480, 320, 460)];
    
    [UIView commitAnimations];
}

- (IBAction)decreaseYear:(id)sender {
    currentYear --;
    [self performSelector:@selector(refreshField)];
}
- (IBAction)increaseYear:(id)sender {
    currentYear ++;
    [self performSelector:@selector(refreshField)];
}

- (IBAction)decreaseMonth:(id)sender {
    currentMonth --;
    if(currentMonth == 0)
    {
        currentMonth = 12;
    }
    [self performSelector:@selector(refreshField)];
}
- (IBAction)increaseMonth:(id)sender {
    currentMonth ++;
    if(currentMonth == 13)
    {
        currentMonth = 1;
    }
    [self performSelector:@selector(refreshField)];
}

- (IBAction)decreaseQuarter:(id)sender {
    currentQuarter--;
    if(currentQuarter == 0)
    {
        currentQuarter = 4;
    }
    [self performSelector:@selector(refreshField)];
}
- (IBAction)increaseQuarter:(id)sender {
    currentQuarter++;
    if(currentQuarter == 5)
    {
        currentQuarter = 1;
    }
    [self performSelector:@selector(refreshField)];
}
- (IBAction)resetTime:(id)sender {
    [self performSelector:@selector(resetTime)];
}
- (IBAction)chooseTimeDate:(id)sender {
    tagForDate = [sender tag];
    NSLog(@"TAR MODE: %i", tagForDate);
    [self createDatePickerView];
    
    //[self hideTabBar:gTabBarController];
}

- (void) setType:(NSInteger) timeType
{
    numTimeMode = [NSNumber numberWithInt:timeType];
}
- (void) setFromDate: (NSDate *) date
{
    fromeDate = date;
}
- (void) setToDate: (NSDate *) date
{
    toDate = date;
}

#pragma mark - MonthViewDelegate
- (void) createDatePickerView {
    
    if(pickerViewPopup == nil)
    {
        pickerViewPopup = [[UIActionSheet alloc] initWithTitle:nil delegate:nil cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles:nil];
        
        [pickerViewPopup setActionSheetStyle:UIActionSheetStyleBlackTranslucent];
        
        UIToolbar *pickerToolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
        pickerToolbar.barStyle = UIBarStyleBlackOpaque;
        [pickerToolbar sizeToFit];
        
        NSMutableArray *barItems = [[NSMutableArray alloc] init];
        
        UIBarButtonItem *doneBtn = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(doneDateButtonPressed:)];
        [barItems addObject:doneBtn];
        
//        UIBarButtonItem *flexSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
//        [barItems addObject:flexSpace];
//        
//        UIBarButtonItem *cancelBtn = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(cancelDateButtonPressed:)];
//        [barItems addObject:cancelBtn];
        
        [pickerToolbar setItems:barItems animated:YES];
        
        if(monthViewCalendar == nil)
        {
            monthViewCalendar = [[TKCalendarMonthView alloc] initWithSundayAsFirst:NO];
            monthViewCalendar.delegate  = self;
            monthViewCalendar.dataSource = self;
            //NSLog(@"MONTH %f x %f", monthViewCalendar.bounds.size.width, monthViewCalendar.bounds.size.height);
            [monthViewCalendar reload];
        }
        [monthViewCalendar setFrame:CGRectMake(0, 44, 320, monthViewCalendar.bounds.size.height)];
        pickerViewPopup.clipsToBounds=YES;
    
        [pickerViewPopup addSubview:pickerToolbar];
        [pickerViewPopup addSubview:monthViewCalendar];
        //[pickerViewPopup setBounds:CGRectMake(0, 0, 320, 416)];
        [pickerViewPopup showInView:self.view];
        [self popUpRefreshFrame];
        
        //[self popUpRefreshFrame];
        
    }else
    {
        [pickerViewPopup showInView:self.view];
        [self popUpRefreshFrame];
    }
    
}

-(void)popUpRefreshFrame
{
    [UIView beginAnimations:@"resize_animation" context:NULL];
    [UIView setAnimationDuration:0.1];
    
    pickerViewPopup.clipsToBounds=YES;
    [pickerViewPopup setFrame:CGRectMake(0.0, 460 - monthViewCalendar.bounds.size.height - 44, 320, monthViewCalendar.bounds.size.height + 44)];
    
    [UIView commitAnimations];
}

-(void)doneDateButtonPressed:(id)sender{
   
    ((folyAppDelegate *)[[UIApplication sharedApplication]delegate]).navigationController.hidesBottomBarWhenPushed = NO;
    [pickerViewPopup dismissWithClickedButtonIndex:1 animated:YES];
    
}

-(void)cancelDateButtonPressed:(id)sender{
  
    [pickerViewPopup dismissWithClickedButtonIndex:1 animated:YES];

}

#pragma mark - Month View Delegate


- (NSArray*) calendarMonthView:(TKCalendarMonthView*)monthView marksFromDate:(NSDate*)startDate toDate:(NSDate*)lastDate{
	return nil;
}

-(void)calendarMonthView:(TKCalendarMonthView *)monthView didSelectDate:(NSDate *)date
{
    NSLog(@"%@", date);
    if(tagForDate == 1)
    {
        fromeDate = date;
    }else
    {
        toDate = date;
    }
    //[self performSelector:@selector(dismisPopupView) withObject:nil afterDelay:1];
    [self refreshField];
}

-(void)dismisPopupView
{
    [pickerViewPopup dismissWithClickedButtonIndex:1 animated:YES];
}

- (void) calendarMonthView:(TKCalendarMonthView*)monthView monthDidChange:(NSDate*)month animated:(BOOL)animated
{
    [self performSelector:@selector(popUpRefreshFrame)];
}

#pragma mark - addtions
// Method implementations
- (void)hideTabBar:(UITabBarController *) tabbarcontroller
{
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.5];
    
    for(UIView *view in tabbarcontroller.view.subviews)
    {
        if([view isKindOfClass:[UITabBar class]])
        {
            [view setFrame:CGRectMake(view.frame.origin.x, 480, view.frame.size.width, view.frame.size.height)];
        } 
        else 
        {
            [view setFrame:CGRectMake(view.frame.origin.x, view.frame.origin.y, view.frame.size.width, 480)];
        }
    }
    
    [UIView commitAnimations];   
}

- (void)showTabBar:(UITabBarController *) tabbarcontroller
{       
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.5];
    for(UIView *view in tabbarcontroller.view.subviews)
    {
        NSLog(@"%@", view);
        
        if([view isKindOfClass:[UITabBar class]])
        {
            [view setFrame:CGRectMake(view.frame.origin.x, 431, view.frame.size.width, view.frame.size.height)];
            
        } 
        else 
        {
            [view setFrame:CGRectMake(view.frame.origin.x, view.frame.origin.y, view.frame.size.width, 431)];
        }
    }
    
    [UIView commitAnimations]; 
}



@end
